import request, { ApiError } from './request'

const version = {
  url: '/api/v1/version'
}

const publickey = {
  url: '/api/v1/auth/publickey'
}

const currentUser = {
  url: '/api/v1/auth/current'
}

const permissions = {
  url: '/api/v1/users/permissions',
  condition: ['can', 'info.public']
}

const roles = {
  url: '/api/v1/users/roles',
  condition: ['can', 'info.public']
}

const types = {
  url: '/api/v1/types',
  condition: ['can', 'info.public']
}

const contacts = {
  url: '/api/v1/messages/private/contacts',
  condition: ['can', 'messages.private']
}

const privateMessageCount = {
  url: '/api/v1/messages/private/count',
  condition: ['can', 'messages.private']
}

/**
 * 混合请求
 * @param {Array|Object} requests 请求列表
 */
export function mixedRequests(requests) {
  return request({
    url: '/api/v1/mixed',
    method: 'post',
    data: requests
  })
}

export function standardUnpack(total) {
  const result = {}
  if (typeof total === 'object') {
    for (const key in total) {
      const response = total[key]
      if (response.executed) {
        if (response.status >= 200 && response.status < 400) {
          result[key] = response.data
        } else {
          result[key] = new ApiError(response.status, response.data.message)
        }
      } else {
        result[key] = null
      }
    }
    return result
  } else {
    throw new Error('返回响应数据格式错误')
  }
}

function standardMixedRequests(description) {
  return mixedRequests(description).then(standardUnpack)
}

export function initialize() {
  return standardMixedRequests({
    version,
    publickey,
    currentUser,
    permissions,
    roles,
    types,
    contacts,
    privateMessageCount
  })
}

export function fetchPublicInfo() {
  return standardMixedRequests({
    permissions,
    roles,
    types,
    contacts,
    privateMessageCount
  })
}

export function readPrivateMessages(messages) {
  const unreadMessages = messages.filter(it => it.is_read === false)
  if (unreadMessages.length === 0) {
    return Promise.resolve({})
  }
  const readRequests = unreadMessages.map(it => ({
    url: `/api/v1/messages/private/${it.id}`
  }))
  const description = {}
  for (const i in readRequests) {
    description[i] = readRequests[i]
  }
  description.privateMessageCount = privateMessageCount
  return standardMixedRequests(description)
}
